import React, { useEffect, useState } from 'react'
import { useDidShow, useDidHide } from '@tarojs/taro'
import Taro from '@tarojs/taro'
import { AppContext, initialState, AppState } from './store'
import { deepSeekService } from './services/deepseek'
import type { Locale } from './i18n'
// 全局样式
import './app.scss'

function App(props) {
  const [state, setState] = useState<AppState>(initialState)

  // 初始化
  useEffect(() => {
    // 从本地存储加载配置
    const locale = Taro.getStorageSync('locale') || 'zh'
    const apiKey = Taro.getStorageSync('apiKey') || ''
    
    setState({
      locale: locale as Locale,
      apiKey
    })

    if (apiKey) {
      deepSeekService.setApiKey(apiKey)
    }
  }, [])

  // 设置语言
  const setLocale = (locale: Locale) => {
    setState(prev => ({ ...prev, locale }))
    Taro.setStorageSync('locale', locale)
  }

  // 设置API Key
  const setApiKey = (apiKey: string) => {
    setState(prev => ({ ...prev, apiKey }))
    Taro.setStorageSync('apiKey', apiKey)
    deepSeekService.setApiKey(apiKey)
  }

  // 对应 onShow
  useDidShow(() => {})

  // 对应 onHide
  useDidHide(() => {})

  return (
    <AppContext.Provider value={{ state, setLocale, setApiKey }}>
      {props.children}
    </AppContext.Provider>
  )
}

export default App

